package com.huike.framework.aspectj;

import com.huike.clues.domain.SysOperLog;
import com.huike.clues.service.ISysOperLogService;
import com.huike.common.annotation.Log;
import com.huike.common.core.domain.model.LoginUser;
import com.huike.common.utils.JsonUtils;
import com.huike.common.utils.ServletUtils;
import com.huike.common.utils.StringUtils;
import com.huike.common.utils.ip.AddressUtils;
import com.huike.common.utils.ip.IpUtils;
import com.huike.common.utils.spring.SpringUtils;
import com.huike.framework.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * 日志切入点
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    private ISysOperLogService operLogService;

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.huike.common.annotation.Log)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            // 获取注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }

            // 获取当前的用户
            LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
            // 数据库日志
            SysOperLog operLog = new SysOperLog();
            operLog.setStatus(0); // 操作状态：0=正常
            operLog.setOperName(loginUser != null ? loginUser.getUsername() : "");
            operLog.setOperTime(new Date());

            // 设置IP地址
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            operLog.setOperIp(ip);
            // 获取当前用户的操作地点
            operLog.setOperLocation(AddressUtils.getRealAddressByIP(ip));


            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");

            // 处理设置注解上的参数
            getControllerMethodDescription(controllerLog, operLog);

            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());

            // 设置请求URL
            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());

            // 设置请求参数
            operLog.setOperParam(JsonUtils.toJsonString(joinPoint.getArgs()));

            // 异常信息
            if (e != null) {
                operLog.setStatus(1); // 操作状态：1=异常
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }

            // 设置返回结果
            if (jsonResult != null) {
                operLog.setJsonResult(JsonUtils.toJsonString(jsonResult));
            }

            // 异步保存日志
            operLogService.saveOperLog(operLog);
        } catch (Exception exp) {
            log.error("日志记录异常: {}", exp.getMessage());
        }
    }

    /**
     * 获取注解中对方法的描述信息
     */
    private void getControllerMethodDescription(Log log, SysOperLog operLog) {
        operLog.setTitle(log.title());
        operLog.setBusinessType(log.businessType().ordinal());
        operLog.setOperatorType(log.operatorType().ordinal());
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }
}